import 'dart:io';

import 'package:cbec_app/components/base/base_ctr.dart';
import 'package:cbec_app/components/http/network.dart';
import 'package:cbec_app/routes/routes.dart';
import 'package:cbec_app/utils/AppData.dart';
import 'package:cbec_app/utils/OssUpload.dart';
import 'package:cbec_app/utils/Tools.dart';
import 'package:cbec_app/utils/logger.dart';
import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:wechat_camera_picker/wechat_camera_picker.dart';

import '../../../components/app_conifg.dart';

class AfterPopController extends BaseController {
  int afterSaleStyle = 1;

  ///订单详情
  Map<String, dynamic> data = {};

  ///订单号
  String orderId = '';

  ///选中的商品
  List goodsList = [];

  ///标题
  var pageTitle = '退款退货'.obs;

  ///初始数量
  var num = 1.obs;

  ///退换货原因
  List reasonList = [];

  ///退换货原因值
  var reasonValued = 0.obs;

  ///退换货原因文本
  var reasonTextd = '选择申请原因'.obs;

  ///退换货类型
  int type = 1;

  ///退货原因
  TextEditingController reasonTxtCtr = TextEditingController();

  ///图片列表
  List<AssetEntity>? imageList = [];

  List<String>? imageUrlList = [];
  Map<String, dynamic> membership_ata = {};

  @override
  void onInit() {
    super.onInit();
    getMineData();
  }

  void setOrderId(String Id) {
    orderId = Id;
    getOrderDetail();
  }

  void getMineData() {
    Network.getMine().then((value) {
      membership_ata = value;
      update();
    }).catchError((onError) {});
  }

  ///初始化
  void init() {
    goodsList = [];
    print("已清空");
  }

  ///选中商品
  void selectGoods(bool selected, Map item) {
    if (selected == true) {
      //选中加入数组
      print('选中加入数组 $item');
      goodsList.add({'item': item, "goodsNumber": 1});
    } else {
      num.value = 1;
      //取消选中从数组中移除
      for (var element in goodsList) {
        if (element['item']['goodsOrderId'] == item['goodsOrderId']) {
          goodsList.remove(element);
        }
      }
    }

    print('goodsList == $goodsList');
  }

  ///增加数量
  void setNum(String goodsOrderId, int num) {
    for (var element in goodsList) {
      if (element['item']['goodsOrderId'] == goodsOrderId) {
        element['goodsNumber'] = num;
      }
    }
  }

  ///下一步
  void next(int currentType) {
    if (goodsList.isEmpty) {
      Tools.showToast("请先选择要售后的商品");
      return;
    } else {
      Get.back();
      Map<String, dynamic> params = {};
      List<Map<String, dynamic>> _goodslist = [];
      print('goodsList == $goodsList');
      for (var element in goodsList) {
        _goodslist.add({"goodsId": element['item']['goodsId'], "goodsNumber": afterSaleStyle == 1 ? element['goodsNumber'] : element['item']['buyNum']});
      }
      params['goodsList'] = _goodslist;
      params['orderId'] = orderId;
      params['client'] = GetPlatform.isIOS ? AppConfig.clientIos : AppConfig.clientAndroid;

      switch (currentType) {
        case 0:
          type = 1;
          pageTitle.value = '退款退货';
          params['refundType'] = type;

          print('退货退款======$params');
          orderReturnPrepare(params);
          break;
        case 1:
          pageTitle.value = '换货';
          type = 3;
          params['refundType'] = type;
          orderReturnPrepare(params);
          break;
        case 2:
          type = 0;
          Get.toNamed(Routes.baojia);
          break;

        default:
      }
    }
  }

  //确认选择原因
  void choiseReason(int reasonValue, String reasonText) {
    reasonTextd.value = reasonText;
    reasonValued.value = reasonValue;
    Get.back();
  }

  //提交换货原因和图片
  void submitReason() {
    if (reasonTxtCtr.text == '') {
      Tools.showToast("请填写原因");
      return;
    }
    // print(reasonTxtCtr.text);
    Get.back();
  }

  //提交申请
  void submit() async {
    Tools.showLoading();
    if (imageList!.isNotEmpty) {
      List<File> fileList = [];
      imageList!.forEach((element) async {
        File? file = await element.file;
        fileList.add(file!);
      });
      imageUrlList = await OssUpload.upoladFiles(fileList);
    }

    Map<String, dynamic> params = {};
    List<Map<String, dynamic>> _goodslist = [];

    for (var element in goodsList) {
      _goodslist.add({"goodsId": element['item']['goodsId'], "goodsNumber": afterSaleStyle == 1 ? element['goodsNumber'] : element['item']['buyNum']});
    }
    params['client'] = GetPlatform.isIOS ? AppConfig.clientIos : AppConfig.clientAndroid;
    params['goodsList'] = _goodslist;
    params['images'] = imageUrlList;
    params['orderId'] = orderId;
    params['reasonInfo'] = reasonTxtCtr.text;
    params['reasonWay'] = reasonValued.value;
    params['refundType'] = type;
    params['sid'] = AppData.sid;

    logger.i('请求参数params == $params');

    return Network.applyReturn(params).then((value) {
      print(value);
      Tools.hideLoading();
      Tools.showToast('提交成功');
      Get.back();
    }).catchError((onError) {
      print(onError);
      Tools.hideLoading();
    });
  }

  Future orderReturnPrepare(Map params) {
    return Network.getRefundPrepare(params).then((value) {
      Tools.hideLoading();
      reasonList = value['refundReasonList'];
      Get.toNamed(Routes.tuikuan);
    }).catchError((onError) {
      print(onError);
      Tools.showToast(onError.toString());
    });
  }

  ///获取退换货原因
  Future resonList() {
    Tools.showLoading();
    return Network.getRefundReason().then((value) {
      reasonList = value;
      Tools.hideLoading();
      Get.toNamed(Routes.tuikuan);
    }).catchError((onError) {
      print(onError);
      Tools.hideLoading();
    });
  }

  //上传图片或视频
  Future<void> upload(context) async {
    final AssetEntity? entity = await CameraPicker.pickFromCamera(context);
    imageList!.add(entity!);
    update();
    Get.back();
  }

//获取详情
  void getOrderDetail() {
    Network.getOrderDetail(orderId).then((value) {
      Tools.hideLoading();
      print('获取详情 $value');
      data = value;
      update();
    }).catchError((error) {
      Tools.hideLoading();
      print(error);
    });
  }
}
